package com.cxh.controller.sys;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.cxh.base.BaseController;
import com.cxh.entity.SysMenu;
import com.cxh.entity.SysUser;
import com.cxh.util.CommonUtility;
import com.cxh.util.DateUtility;
import com.cxh.util.json.JSONUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import javax.persistence.Column;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 类说明：
 * @author  ChenXH
 * @date  2018-11-29 11:14:13
 */
@Controller
@RequestMapping(value = "/controller/sysMenu")
public class SysMenuController extends BaseController {

    /**
     * 方法说明：进入页面
     * @author  ChenXH
     * @date  2018-11-29 11:14:13
     */
    @RequestMapping(value = "/list")
    public ModelAndView list (HttpServletRequest request, HttpServletResponse response){
        ModelAndView model =  new ModelAndView();
        model.setViewName("sys/sysMenu/sysMenuList");
        return model;
    }

    /**
     * 方法说明：获得表格数据
     * @author  ChenXH
     * @date  2018-11-29 11:14:13
     */
    @RequestMapping(value = "/showList")
    @ResponseBody
    public String showList (HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
        String json="";
        //获得  页码数
        Integer page=CommonUtility.isEmpty(params.get("page"))?1:Integer.parseInt(params.get("page")+"");
        //获得 每页的行数
        Integer limit=CommonUtility.isEmpty(params.get("limit"))?10:Integer.parseInt(params.get("limit")+"");
        //设置 分页参数
        PageHelper.startPage(page,limit);
        //调用 查询方法
        List<SysMenu> sysMenuList=sysMenuService.loadPageList(params);
        //处理数据
        PageInfo<SysMenu> pageInfo=new PageInfo<SysMenu>(sysMenuList);
        try {
            //转换 时间格式/并将数据转换成json字符串
            JsonConfig jsonConfig = JSONUtil.getJsonConfig(DateUtility.DateFormat1);
            json= JSONUtil.toLayUIJSONAll(pageInfo.getTotal(),pageInfo.getList(), jsonConfig);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }


    /**
     * 方法说明：进入编辑页面
     * @author  ChenXH
     * @date  2018-11-29 11:14:13
     */
    @RequestMapping(value = "/edit")
    public ModelAndView edit (HttpServletRequest request, HttpServletResponse response){
        //获得要修改数据的Id
        int entityId=CommonUtility.isEmpty(request.getParameter("entityId"))?0:Integer.parseInt(request.getParameter("entityId"));
        ModelAndView model=new ModelAndView();
        try {
            //判断是 修改  还是 新增
            if (!CommonUtility.isEmpty(entityId)&&entityId>0) {
                HashMap<String, Object> hashMap = new HashMap<String,Object>();
                hashMap.put("id", entityId);
                List<SysMenu> sysMenuList = sysMenuService.getMenu(hashMap);
                // 进行数据准备
                model.addObject("sysMenu",sysMenuList.get(0));
            }
            //返回视图位置
            model.setViewName("sys/sysMenu/sysMenuForm");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return model;
    }

    /**
     * 方法说明：保存/修改
     * @author  ChenXH
     * @date  2018-11-29 11:14:13
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public String save (HttpServletRequest request, HttpServletResponse response,@RequestParam  Map<String,Object> jsonMap,SysMenu sysMenu1){
        //执行状态（0成功；1失败）
        int flag=0;
        int entityId=CommonUtility.isEmpty(jsonMap.get("entityId"))?0:Integer.parseInt(jsonMap.get("entityId")+"");
        //进行 修改
        if(entityId>0){
            SysMenu sysMenu=sysMenuService.selectByPrimaryKey(entityId);
            if(!CommonUtility.isEmpty(sysMenu)){
            	//查询是哪一级别的菜单，不支持第三级别的菜单
            	boolean an = sysMenuService.getMuenLevel(sysMenu.getParentid());
            	if(an == false){
            		return "3";
            	}
                try {
                    //修改
                    sysMenuService.updateByPrimaryKey(sysMenu1);
                    //operationLog(request, "修改用户" + user.getLoginName(), TableConstants.LOG_TYPES_EDIT);
                }catch (Exception e) {
                    flag = 1;
                    e.printStackTrace();
                }
            }else{
                flag=1;
            }
        }else{
            try {
            	//查询父节点的id是否存在
            	String parentid = sysMenu1.getParentid();
            	if(!"0".equals(parentid)){
            		//查询父节点存在不存在
            		Example example = new Example(SysMenu.class);
            		Criteria createCriteria = example.createCriteria();
            		createCriteria.andEqualTo("id",parentid);
            		List<SysMenu> sysMenuList = sysMenuService.selectByExample(example);
            		if(sysMenuList.size() == 0){
            			//表示父节点不存在
            			return "2";
            		}
            	}
            	//查询是哪一级别的菜单，不支持第三级别的菜单
            	boolean an = sysMenuService.getMuenLevel(parentid);
            	if(an == false){
            		return "3";
            	}
            	
                //新增
                sysMenuService.insert(sysMenu1);
                //operationLog(request, "添加用户" + user.getLoginName(), TableConstants.LOG_TYPES_ADD);
            }catch (Exception e) {
                flag = 1;
                e.printStackTrace();
            }
        }

        return flag+"";
    }

    /**
     * 方法说明：删除
     * @author  ChenXH
     * @date  2018-11-29 11:14:13
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public String delete (HttpServletRequest request, HttpServletResponse response){
        int entityId=CommonUtility.isEmpty(request.getParameter("entityId"))?0:Integer.parseInt(request.getParameter("entityId"));
        //执行状态（0成功；1失败）
        int flag = 0;
        if(entityId>0){
            SysMenu sysMenu = sysMenuService.selectByPrimaryKey(entityId);
            if(!CommonUtility.isEmpty(sysMenu)){
                //sysMenu.setIsDel(0);
                try {
                    sysMenuService.deleteSysMenu(sysMenu);
                    //operationLog(request, "删除用户" + user.getLoginName(), TableConstants.LOG_TYPES_DEL);
                }catch (Exception e) {
                	String message = e.getMessage();
                	if("2".equals(message)){
                		flag = 2;
                	}else{
                		flag = 1;
                	}
                    e.printStackTrace();
                }
            }
        }
        return flag+"";
    }

    
    @RequestMapping("/getMenuTree")
    @ResponseBody
    public String getMenuTree(HttpServletRequest request, HttpServletResponse response){
    	//根据用户查询菜单信息
    	List<SysMenu> sysMenuList = sysMenuService.getMenu(null);
    	ArrayList<Object> arrayList = new ArrayList<Object>();
    	//完全是为了将id的int类型转为String类型，心累，前端要求的必须是String
        JSONArray fromObject = JSONArray.fromObject(sysMenuList);
        for (Object object : fromObject) {
        	JSONObject fromObject2 = JSONObject.fromObject(object);
        	Object object2 = fromObject2.get("id");
        	fromObject2.put("id", object2.toString());
        	arrayList.add(fromObject2);
		}
        Gson gson = new Gson();
        //组装json
        HashMap<String, Object> jsonMap = new HashMap<String,Object>();
        jsonMap.put("msg", "");
        jsonMap.put("code", 0);
        jsonMap.put("data", JSONArray.fromObject(arrayList));
        
        jsonMap.put("count", sysMenuList.size());
        jsonMap.put("is", true);
        jsonMap.put("tip", "操作成功！");
        return gson.toJson(jsonMap);
    }

}
